package com.dunqi.gpm.cangxi;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.Intent;

import com.dunqi.gpm.cangxi.common.util.CommonUtil;
import com.dunqi.gpm.cangxi.common.util.RxBus;
import com.dunqi.gpm.cangxi.common.util.SharedPreferencesUtils;
import com.dunqi.gpm.cangxi.mine.LoginActivity;
import com.dunqi.gpm.cangxi.mine.bean.User;
import com.dunqi.gpm.cangxi.mine.util.UserUtil;
import com.pgyersdk.crash.PgyCrashManager;

import java.util.ArrayList;

import cn.jpush.android.api.JPushInterface;

/**
 *
 */

public class KongApp extends Application {
    private static Context context;
    public static Context getContext() {
        return context;
    }
    static ArrayList<Activity> activities = new ArrayList<>();
    public static void setContext(Context context) {
        KongApp.context = context;
    }
    @SuppressLint("CheckResult")
    @Override
    public void onCreate() {
        super.onCreate();
        context = this;
        SharedPreferencesUtils.config(this);
        JPushInterface.setDebugMode(false);
        JPushInterface.init(this);
        String id = JPushInterface.getRegistrationID(this);
//        JPushInterface.setAlias(getApplicationContext(), 1, CommonUtil.getDeviceId())
        RxBus.getInstance()
                .register(User.class)
                .subscribe(user -> {
                    UserUtil.clear();
                    KongApp.finishAllActivity();
                    Intent intent = new Intent(getContext(), LoginActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                }, throwable -> {
                    UserUtil.clear();
                    KongApp.finishAllActivity();
                    Intent intent = new Intent(getContext(), LoginActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                });
        if (!WPConfig.INSTANCE.isDebug)
            PgyCrashManager.register(this);
    }

    public static void addActivity(Activity activity) {
        activities.add(activity);
    }

    public static void removeActivity(Activity activity) {
        activities.remove(activity);
    }

    public static void finishAllActivity() {
        for (Activity activity : activities) {
            if (!activity.isFinishing()) {
                activity.finish();
            }
        }
        activities.clear();
    }

}
